package org.altervista.cp.microkernel.io;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;

public class ObjectSerializer {

	private static final int BUFFER_SIZE = 1024;

	public static void readAndWrite(InputStream is, int bufferSize,
			OutputStream os) throws IOException {
		byte[] buffer = new byte[bufferSize];
		for (int rb = 0; (rb = is.read(buffer)) != -1;) {
			os.write(buffer, 0, rb);
		}
		os.flush();
	}

	public ObjectSerializer() {
	}

	public ObjectSerializer(Object object) {
		_object = object;
	}

	public byte[] getBytes() throws IOException {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		writeTo(baos);
		return baos.toByteArray();
	}

	public InputStream getInputStream() throws IOException {
		return new ByteArrayInputStream(getBytes());
	}

	public OutputStream getOutputStream() throws IOException {
		return new ByteArrayOutputStream() {
			public void close() throws IOException {
				try {
					readFrom(new ByteArrayInputStream(buf));
				} catch (ClassNotFoundException e) {
					throw new IllegalStateException(e);
				}
			}
		};
	}

	public Object getObject() {
		return _object;
	}

	public int length() throws IOException {
		return _length;
	}

	public void readFrom(InputStream is) throws ClassNotFoundException,
			IOException {
		_object = new ObjectInputStream(
				new BufferedInputStream(is, BUFFER_SIZE)).readObject();
	}

	public void writeTo(OutputStream os) throws IOException {
		ObjectOutputStream oos = new ObjectOutputStream(
				new BufferedOutputStream(os, BUFFER_SIZE));
		oos.writeObject(_object);
		oos.flush();
	}

	private Object _object;
	private int _length;

}
